//
//  XFUserAccountModel.m
//  SinaBlog_OC
//
//  Created by macs on 15/11/11.
//  Copyright © 2015年 BlackTail. All rights reserved.
//

#import "XFUserAccountModel.h"
#import "AFNetworking.h"
#import "XFNetworkTools.h"

@implementation XFUserAccountModel

- (NSString *)avatar_url {

  if (_avatar_url == nil) {
    _avatar_url = self.account.avatar_large;
  }
  return _avatar_url;
}

- (NSString *)name {

  if (_name == nil) {
    _name = self.account.name;
  }
  return _name;
}

- (NSString *)token {

  if (!_token) {
    _token = self.account.access_token;
  }
  return _token;
}

- (BOOL)isLogin {

  _isLogin = self.account.access_token != nil;

  return _isLogin;
}

- (instancetype)init {
  self = [super init];
  if (self) {
    self.account = [XFAccount getAccount];
  }
  return self;
}

- (void)getAccess_tokenWithCode:(NSString *)code
                      andfinish:(FinishedArray)finish {
  NSString *urlString = @"oauth2/access_token";
  NSDictionary *paremeters = @{
    @"client_id" : kClient_id,
    @"client_secret" : kClient_secret,
    @"grant_type" : @"authorization_code",
    @"code" : code,
    @"redirect_uri" : kRedirect_uri
  };

  [[XFNetworkTools shareNetWorkTools]
      requestJsonDictWithHttpMothod:HTTPMethodPOST
                          Urlstring:urlString
                         Parameters:paremeters
                        AndFinished:^(NSError *error, NSDictionary *dict) {
                          if (error != nil) {
                            NSLog(@"%@", error);
                            return;
                          }
                          XFAccount *account = [XFAccount accountWithDict:dict];
                          //          NSLog(@"%@",account.access_token);
                          [self getUserInfo:account andfinish:finish];
                        }];
}

- (void)getUserInfo:(XFAccount *)account andfinish:(FinishedArray)finish {

  NSString *urlString = @"2/users/show.json";
  NSDictionary *parametter = @{
    @"access_token" : account.access_token,
    @"uid" : account.uid
  };

  [[XFNetworkTools shareNetWorkTools]
      requestJsonDictWithHttpMothod:HTTPMethodGET
                          Urlstring:urlString
                         Parameters:parametter
                        AndFinished:^(NSError *error, NSDictionary *dict) {

                          if (error != nil) {
                            finish(error, nil);
                            return;
                          }
                          account.avatar_large = dict[@"avatar_large"];
                          account.name = dict[@"name"];
                          //归档操作
                          [account saveAccount];
                          NSLog(@"%@", account);
                          finish(nil, nil);
                        }];
}

@end
